/**
 * 设置cookie缓存
 * @param cname
 * @param cvalue
 * @param extime 有效时间，这个是指从当前算起，多长时间后会过期
 */
const setCookie = (cname, cvalue, extime) => {
    let date = new Date()
    date.setTime(date.getTime() + extime)
    let expires = date.toGMTString()
    // 计算好过期时间后再掉过期时间设置
    setCookieWithExpires(cname, cvalue, expires)
}

/**
 * 设置cookie缓存
 * @param cname
 * @param cvalue
 * @param expires 过期时间，这个就是过期时的具体时间
 */
const setCookieWithExpires = (cname, cvalue, expires) => {
    /**
     * document.cookie 设置cookie，并不是说把整个cookie全更新了，只会在已有cookie基础上，新加一个cname cookie
     * 当然如果cname cookie也已存在，则是进行更新覆盖
     * @type {string}
     */
    document.cookie = cname + '=' + cvalue + ';expires=' + expires
}

const getCookie = (cname) => {
    let cvalue = ''
    ;(document.cookie || '').split(';').forEach(pair => {
        pair = pair.trim()
        let crack = pair.indexOf('=')
        if (crack > 0 && crack < pair.length - 1 && pair.slice(0, crack) === cname) {
            cvalue = pair.slice(crack + 1)
        }
    })
    return cvalue
}

const removeCookie = (cname) => {
    let date = new Date()
    date.setTime(date.getTime() - 10)
    let expires = "expires=" + date.toGMTString()
    // 将cookie过期时间调整到比当前早10ms，实现删掉cookie
    document.cookie = cname + "='';" + expires
}

const setLocalStorage = (key, value) => {
    window.localStorage.setItem(key, value)
}

const getLocalStorage = (key) => {
    return window.localStorage.getItem(key) ? window.localStorage.getItem(key) : ''
}

export default {
    setCookie,
    setCookieWithExpires,
    getCookie,
    getLocalStorage,
    setLocalStorage
}
